package com.sddr.common.nacos.api;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.DisposableBean;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

/**
 * @author 山顶洞人郑某
 * @className NacosApi.java
 * @date 2025 07 13
 */
@AllArgsConstructor
public class NacosApi implements DisposableBean { //实现了 DisposableBean 接口，表示此类在 Spring 容器销毁时会执行清理操作。

    private final ConfigService nacosConfigService;

    public String getConfig(String dataId, String group) throws NacosException {
        return nacosConfigService.getConfig(dataId, group, 5000);
    }

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     *
     * @throws Exception in case of shutdown errors. Exceptions will get logged
     *                   but not rethrown to allow other beans to release their resources as well.
     */
    @Override
    public void destroy() throws Exception {
        // 关闭nacos
        nacosConfigService.shutDown();
    }

    /**
     * 监听Nacos中心配置信息
     * @param dataId 配置ID
     * @param group 配置组
     * @param threadPool 线程池
     * @param nacosListener 监听器
     * @throws NacosException 监听异常
     */
    public void listenConfig(String dataId, String group, ExecutorService threadPool, NacosListener nacosListener ) throws NacosException {
        Listener listener = new Listener() {
            @Override
            public Executor getExecutor() {
                return threadPool;
            }

            @Override
            public void receiveConfigInfo(final String s) {
                nacosListener.callBack(s);
            }
        };
        //添加监听器
        nacosConfigService.addListener(dataId, group,listener);
    }
}
